"use strict";
let jsdom = require('jsdom')
let fs = require('fs')
let path = require('path')
let prompt = require('prompt')
let cssbeautify = require('cssbeautify')
let SVGO = require('svgo'), svgo = new SVGO()

// files to be processed
let reFile = /^(ic.*|logo.*|bg.*)\.svg$/, fileNames = fs.readdirSync(path.resolve('.')).filter(fileName => reFile.test(fileName))

const // output files
      OUTPUT_FOLDER = './css/', OUTPUT_FILENAME_CSS = 'svg-icon.css', OUTPUT_FILENAME_HTML = 'svg-icon.html',
			CSS_BASE_CLS_TPL = `.ic-svg { background-repeat: no-repeat; display: inline-block; vertical-align: middle; } .ic-svg-scale { background-size: 100%; }\n`, LOCAL_FILE = 'local.json'

let css = [CSS_BASE_CLS_TPL], html = ['<input type="text" style="position: fixed; top: -10px; left: -10px; width: 6px; height: 1px;" id="copy">']

function processFile(fileNames, idx) {
	idx = idx || 0
	if (idx >= fileNames.length) { // all svg processed

    // write css
		fs.writeFileSync(path.join(OUTPUT_FOLDER, OUTPUT_FILENAME_CSS), cssbeautify(css.join('\n')))

    // write html
		let htmlContent
		jsdom.env({
			file: OUTPUT_FILENAME_HTML,
			defaultEncoding: 'utf-8',
			done(err, win) {
				if (!err) {
					win.document.body.innerHTML = html.join('\n')
					htmlContent = win.document.documentElement.outerHTML
					fs.writeFileSync(OUTPUT_FILENAME_HTML, htmlContent)
				} else {
					console.error(err)
				}
			}
		})
		return;
	}

	let fileName = fileNames[idx]
	fs.readFile(fileName, 'utf8', (err, data) => {
		if (err) {
			throw err
		}

		console.info(fileName)
		svgo.optimize(data, svgOptimized => {
			if (svgOptimized.error) {
				throw svgOptimized.error
			}

			// append css
			let selector = fileName.replace(/\.\w+$/, '').replace('_actived', '.actived').replace(/_|\s+/g, '-').replace(/#/g, '.'),
					svgInfo = svgOptimized.info
			css.push(`.${selector} {
				  background-image: url('data:image/svg+xml;charset=utf8,${encodeURIComponent(svgOptimized.data)}');
				  width: ${svgInfo.width}px;
				  height: ${svgInfo.height}px;
				  background-size: 100%;
				}`)

			// append html
			let classes = `ic-svg ${selector.replace(/\./g, ' ')}`
			html.push(`<div data-filename="${fileName}" title="${classes} 点击可复制" class="${classes}"></div>`)
			
			processFile(fileNames, ++idx)
		})
	})
}

processFile(fileNames)
